package com.atguigu.partition;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;
import java.util.List;

/**
 * @author yhm
 * @create 2024-04-02 15:19
 */
public class Test01_CustomPartition {
    public static void main(String[] args) throws Exception {
        // 1. 创建环境
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 8081);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        // 2. 读取数据源
        List<WaterSensor> waterSensors = Arrays.asList(new WaterSensor("sensor_1", 1000L, 1),
                new WaterSensor("sensor_2", 2000L, 3),
                new WaterSensor("sensor_3", 3000L, 2),
                new WaterSensor("sensor_4", 4000L, 4)
        );
        DataStreamSource<WaterSensor> dataStreamSource = env.fromCollection(waterSensors);

        // 可以使用自定义分区器来完成分区
        // 代码中使用的分区编号是0,1
        // 打印控制台使用的分区编号是1,2
        dataStreamSource.partitionCustom(new Partitioner<Integer>() {
            @Override
            public int partition(Integer key, int numPartitions) {

                return key % numPartitions;
            }
        }, new KeySelector<WaterSensor, Integer>() {
            @Override
            public Integer getKey(WaterSensor value) throws Exception {
                return value.vc;
            }
        }).print();

//        dataStreamSource.print();


        // 3. 处理数据

        // 4. 输出

        // 5. 执行环境
        env.execute();
    }
}
